# 定义数据库工具类
import pymysql


class DB_Tools(object):
#     创建连接
#     类方法
    @classmethod
    def __create_conn(cls):
        conn = pymysql.connect(host="211.103.136.244", port=7061, user="student",
                               password="iHRM_student_2021", database="ihrm", charset="utf8")
        return conn


#     查询
    @classmethod
    def query_db(cls,sql):
        my_conn=None
        my_cursor=None
        re=None
        try:
            # 创建连接
            my_conn = DB_Tools.__create_conn()
            #     创建游标
            my_cursor = my_conn.cursor()
            #     执行sql语句
            my_cursor.execute(sql)
            # 获取数据集
            re = my_cursor.fetchall()
        except Exception as e:
            print("查询出错：",e)
        finally:
            # 关闭游标
            my_cursor.close()
            # 关闭连接
            my_conn.close()
            # 返回查询结果
            return re

    # 增删改
    @classmethod
    def iud_db(cls,sql):
        my_conn = None
        my_cursor = None
        try:
            # 创建连接
            my_conn = DB_Tools.__create_conn()
            #  创建游标
            my_cursor = my_conn.cursor()
            #  执行sql语句
            my_cursor.execute(sql)
            #  查看执行结果
            print("Affected rows:",my_conn.affected_rows())
            my_conn.commit()
        except Exception as e:
            print("查询出错：", e)
            my_conn.rollback()
        finally:
            # 关闭游标
            my_cursor.close()
            # 关闭连接
            my_conn.close()

if __name__ == '__main__':
    DB_Tools.iud_db("UPDATE `as` set   `read` =`read`+1 WHERE id>0")